package com.tema.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import com.sun.mail.util.MailSSLSocketFactory;
import com.tema.entities.*;
import com.tema.mapper.*;
import org.apache.commons.math3.analysis.function.Abs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.tema.forms.CompanyForm;
import com.tema.forms.RecordForm;

@Controller
@RequestMapping("/companyManage")
public class CompanyManageController {
	@Autowired
	CompanyRequestMapper companyRequestMapper;
	@Autowired
	UserMapper userMapper;
	@Autowired
	CompanyMapper companyMapper;
	@Autowired
	JobMapper jobMapper;
	@Autowired
	JudgeMapper judgeMapper;
	
	Record record = null;
	
	User user;
	@RequestMapping("/signCompany")
	public String toSignCompany(HttpSession session, Model model) {
		model.addAttribute("newCompany", new CompanyForm());
		user = (User) session.getAttribute("loginUser");
		model.addAttribute("loginUser", user);
		return "companyManager/signCompany";
	}
	
	@GetMapping
	public String myCompany(HttpSession session, Model model) {
		if (session.getAttribute("loginUser") == null) {
			return "redirect:/login";
		}
		user = (User) session.getAttribute("loginUser");
		if (!user.getIsAdmin() || user.getCompany() == null) {
			return "redirect:/home";
		}
		model.addAttribute("loginUser", user);
		System.out.println(user.getCompany().getId());
		List<Integer> integers = userMapper.findPageByCompany(user.getCompany().getId());
		List<User> users = new ArrayList<User>();
		for (Integer integer : integers) {
			users.add(getUser(integer));
		}
		model.addAttribute("employees", users);
		return "companyManager";
	}
	
	@PostMapping("/signCompany")
	public String signCompany(@Valid @ModelAttribute("newCompany") CompanyForm newCompany,
			HttpSession session, Errors errors) {
		if (errors.hasErrors()) {
			return "companyManager/signCompany";
		}
		CompanyRequest companyRequest = new CompanyRequest();
		companyRequest.setName(newCompany.getName());
		companyRequest.setDescription(newCompany.getDescription());
		user = (User) session.getAttribute("loginUser");
		companyRequest.setUser(user);
		companyRequestMapper.insert(companyRequest);
		return "redirect:/home";
	}
	
	@GetMapping("/delete/{id}")
	public String deleteUser(@PathVariable("id") int id, HttpSession session, Model model) {
		if (session.getAttribute("loginUser") == null) {
			return "redirect:login";
		}
		user = (User) session.getAttribute("loginUser");
		if (!user.getIsAdmin() || user.getCompany() == null) {
			return "redirect:/home";
		}
		try {
			sendMail(userMapper.getOne(id).getEmail());
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
		userMapper.setCompany(id, -1);
		return "redirect:/companyManage";
	}
	public void sendMail(String email) throws GeneralSecurityException {
		//reviser and sender
		String to = email;
		String from = "qin7899@qq.com";
		//here is host of mail, I use QQ mail
		String host = "smtp.qq.com";
		Properties properties = System.getProperties();
		properties.setProperty("mail.smtp.host", host);
		properties.put("mail.smtp.auth","true");
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.ssl.socketFactory", sf);

		Session session = Session.getInstance(properties,new Authenticator(){
			@Override
			public PasswordAuthentication getPasswordAuthentication()
			{
				//user and password, remember: DO NOT PUSH PASSWORD TO GITHUB!!!! by zzp
				return new PasswordAuthentication("qin7899@qq.com", "eksvzxpghznddhgc"); //发件人邮件用户名、授权码
			}
		});

		try {
			//create a message to send HTML doc
			MimeMessage message = new MimeMessage(session);

			message.setFrom(new InternetAddress(from));

			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			message.setSubject("抱歉，您已被公司解雇!");
			//insert captcha here
			String htmlText = "您已被所在公司解雇。";
			message.setContent(htmlText, "text/html; charset=UTF-8");
			Transport.send(message);
			System.out.println("Sent message successfully");
		} catch (MessagingException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	@GetMapping("/judge/{id}")
	public String judgeUser(@PathVariable("id") int id, HttpSession session, Model model) {
		if (session.getAttribute("loginUser") == null) {
			return "redirect:login";
		}
		user = (User) session.getAttribute("loginUser");
		if (!user.getIsAdmin() || user.getCompany() == null) {
			return "redirect:/home";
		}
		User judgedUser = getUser(id);
		model.addAttribute("loginUser", user);
		Judge judge = judgeMapper.queryCompanyJudge(id, user.getCompany().getId());
		if (judge != null) {
			model.addAttribute("judgement", judge.getJudgement());
		}
		model.addAttribute("judgedUser", judgedUser);
		return "companyManager/judgeUser";
	}
	
	@RequestMapping(value = "/submitUserJudge", method = GET)
	public String deliveringPackages(@RequestParam(value = "judgement") int judgement,
			@RequestParam(value = "userId") int id, Model model, HttpSession session) {
			User judgedUser = getUser(id);
			Judge newJudege = new Judge();
			user = (User) session.getAttribute("loginUser");
			Judge judge = judgeMapper.queryCompanyJudge(id, user.getCompany().getId());
			
			if (judge == null) {
				newJudege.setJudgement(judgement);
				newJudege.setJudgeDate(new Date());
				newJudege.setUser(judgedUser);
				newJudege.setCompany(user.getCompany());
				judgeMapper.insertCompanyJudge(newJudege);
			}else {
				judge.setJudgement(judgement);
				judge.setJudgeDate(new Date());
				judgeMapper.updateCompanyJudge(judge);
			}
			return "redirect:/companyManage";
	}
	
	@RequestMapping(value = "/recordUser", method = GET)
	public String record(Model model, HttpSession session) {
		if (session.getAttribute("loginUser") == null) {
			return "redirect:login";
		}
		user = (User) session.getAttribute("loginUser");
		if (!user.getIsAdmin() || user.getCompany() == null) {
			return "redirect:/home";
		}
		model.addAttribute("newRecord", new RecordForm());
		model.addAttribute("loginUser", user);
		return "record/inspection.html";
	}

	@RequestMapping(value = "/viewRecord", method = GET)
	public String viewRecord(Model model, HttpSession session) {
		if (session.getAttribute("loginUser") == null) {
			return "redirect:login";
		}
		user = (User) session.getAttribute("loginUser");
		if (!user.getIsAdmin() || user.getCompany() == null) {
			return "redirect:/home";
		}
		model.addAttribute("record", record);
		model.addAttribute("loginUser", user);
		return "record/ViewRecords.html";
	}
	@Autowired
	private JobRequestMapper jobRequestMapper;
	@Autowired
	private AbilityMapper abilityMapper;
	@RequestMapping(value = "/viewAbility/{id}", method = GET)
	public String viewAbility(@PathVariable("id") int id,Model model, HttpSession session) {
		if (session.getAttribute("loginUser") == null) {
			return "redirect:login";
		}
		user = (User) session.getAttribute("loginUser");
		User loginUser = user;
		if (!user.getIsAdmin() || user.getCompany() == null) {
			return "redirect:/home";
		}
		int userid = jobRequestMapper.getUserId(id);
		List<Ability> abilities = abilityMapper.findPageByUserId(userid, 0 , 100);
		model.addAttribute("abilities", abilities);
		model.addAttribute("loginUser", loginUser);
		return "record/ViewAbilities.html";
	}
	@Autowired
	private ResumeMapper resumeMapper;
	@RequestMapping(value = "/viewResumes/{id}",method = GET)
	public String viewResumes(@PathVariable("id") int id,Model model, HttpSession session ){
		if (session.getAttribute("loginUser") == null) {
			return "redirect:login";
		}
		user = (User) session.getAttribute("loginUser");
		User loginUser = user;
		if (!user.getIsAdmin() || user.getCompany() == null) {
			return "redirect:/home";
		}
		int userid = jobRequestMapper.getUserId(id);
		List<Resume> resumes = resumeMapper.findPageByUserId(userid,0,100);
		model.addAttribute("loginUser",loginUser);
		model.addAttribute("resumes",resumes);
		return "record/viewResumes.html";
	}
	
	@PostMapping("/recordUser")
	public String addJob(@Valid @ModelAttribute("newRecord") RecordForm newRecord, Errors errors, HttpSession session, Model model) {
		if (errors.hasErrors()) {
			user = (User) session.getAttribute("loginUser");
			model.addAttribute("loginUser", user);
			return "/recruit/recordUser";
		}
		if (user != null  && (user.getIsHR() || user.getIsAdmin())) {
			System.out.println(user.getCompany().getId());
			record = new Record();
			record.setCompany(user.getCompany());
			
			
			record.setAttendance(newRecord.getAttendance());
			record.setBreakRule(newRecord.getBreakRule());
			record.setPerformance(newRecord.getPerfoemance());
			
		}
		return ("redirect:/home");
	}
	
	
	
	public User getUser(int userId) {
		User returnUser = userMapper.getOne(userId);
		returnUser.setCompany( companyMapper.getJobCompany(returnUser.getId()) );
		Job job = jobMapper.getUserJob(userId);
		returnUser.setJob(job);
		CompanyRelation companyRelation = userMapper.getCompany(userId);
		if (companyRelation != null && companyRelation.getCompanyId() != -1) {
			returnUser.setCompany(companyMapper.getJobCompany(companyRelation.getCompanyId()));
			returnUser.setIsAdmin(companyRelation.getIsAdmin());
			returnUser.setIsHR(companyRelation.getIsHR());
		}else {
			returnUser.setCompany(null);
			returnUser.setIsAdmin(false);
			returnUser.setIsHR(false);
		}
		return returnUser;
	}
}
